package com.efast.dmom.mgmt.service.mes.report.impl;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efast.cafe.commponent.query.service.impl.QueryServiceImpl;
import com.efast.cafe.framework.bean.QueryPageBase;
import com.efast.cafe.portal.bean.query.QueryBean;
import com.efast.cafe.portal.bean.query.QueryConditionBean;
import com.efast.cafe.portal.bean.query.QueryOpBean;
import com.efast.dmom.mgmt.bean.mes.report.IntervalConfigBean;
import com.efast.dmom.mgmt.bean.mes.report.VehicleCarInformationBean;
import com.efast.dmom.mgmt.dao.mes.report.ReportVehicleRetrospectDao;
import com.efast.dmom.mgmt.utils.Assist;
import com.ibm.icu.text.SimpleDateFormat;

import jodd.util.StringUtil;

/**
 * 重写滞留车查询方法,需排除非工作日(筛选条件)
 * @author Administrator
 *
 */
@Service("apiindex533-987")
public class SelectStrandedCarInformationServiceImpl extends QueryServiceImpl{
	
	@Autowired
	private ReportVehicleRetrospectDao reportVehicleRetrospectDao;
	
	@Override	
	public Object queryList(QueryBean querys) {
		QueryPageBase result = new QueryPageBase();
		QueryConditionBean queryConditionBean = querys.getQueryConditionBean();
		List<VehicleCarInformationBean> vehicleCarInformationlist = new ArrayList<VehicleCarInformationBean>();
		int count = 0 ;
		Assist assist = new Assist();
		int start = 0;
		int length = 0;
		//区域名称
		int intervalName = 0;
		//标志是否排除非工作日
		String isTextDay = "";
		if(queryConditionBean!=null) {
			if(queryConditionBean.getStart() == null || queryConditionBean.getLength() == null) {
				queryConditionBean.setStart(0);
				queryConditionBean.setLength(querys.getTemplate().getPagenation());
			}
			assist.setStartRow(queryConditionBean.getStart());
			assist.setRowSize(queryConditionBean.getLength());
			start = assist.getStartRow();
			length = assist.getRowSize();
			List<QueryOpBean> queryOpBeans = queryConditionBean.getQueryOpBeans();
			if (queryOpBeans != null && queryOpBeans.size() > 0) {
				for (QueryOpBean data : queryOpBeans) {
					   if(StringUtil.isNotBlank(data.getKey())&& StringUtil.isNotBlank(data.getValue()) && !data.getKey().equals("intervalName") && !data.getKey().equals("is_text_day")) {
						   if (data.getOpName().equals("包含")) {
								assist.setRequires(Assist.andLike(data.getKey(), "%" + data.getValue() + "%"));
							}
							if (data.getOpName().equals("等于")) {
								assist.setRequires(Assist.andEq(data.getKey(), data.getValue()));
							}
							if (data.getOpName().equals("介于(包含)")) {
								String[] split = data.getValue().split("~");
								String beginTime = "";
								String endTime = "";
								if(split!=null &&split.length>1) {
									 beginTime = split[0];
									 endTime = split[1];
								}
								assist.setRequires(Assist.andGte(data.getKey(), beginTime));
								assist.setRequires(Assist.andLte(data.getKey(), endTime));
							}
					   } else if (StringUtil.isNotBlank(data.getKey())&& StringUtil.isNotBlank(data.getValue())&&data.getKey().equals("intervalName")&&!data.getKey().equals("is_text_day")) {
						   intervalName = Integer.valueOf(data.getValue()).intValue();
					   } else if (StringUtil.isNotBlank(data.getKey())&& StringUtil.isNotBlank(data.getValue())&& !data.getKey().equals("intervalName")&& data.getKey().equals("is_text_day")) {
						   isTextDay = data.getValue(); 
					   }
				}
			}
	}
		StringBuilder dynamicRegionSql = new StringBuilder();
		//获取区间配置表信息
		List<IntervalConfigBean> intervalConfigList = reportVehicleRetrospectDao.getIntervalConfigData();
		List<IntervalConfigBean> intervalConfigData = new ArrayList<IntervalConfigBean>();
		if (intervalName != 0) {
			for(IntervalConfigBean bean:intervalConfigList) {
					if(intervalName == bean.getIntervalConfigId()) {
						intervalConfigData.add(bean);
				}
			}
		} else {
			for(IntervalConfigBean bean:intervalConfigList) {
					intervalConfigData.add(bean);
			}
		}
		//获取区间配置车间类型
		List<IntervalConfigBean> intervalConfigWorkShopTypeList = reportVehicleRetrospectDao.selectIntervalConfigWorkShopType();
		//获取滞留车信息
		if(intervalConfigData != null && intervalConfigData.size()>0 && intervalConfigWorkShopTypeList != null && intervalConfigWorkShopTypeList.size() > 0) {
			for (IntervalConfigBean data:intervalConfigData) {
				dynamicRegionSql.delete(0, dynamicRegionSql.length());
				List<VehicleCarInformationBean> strandedCarList = reportVehicleRetrospectDao.SelectStrandedCarInformation(data,assist);
				if(isTextDay == null || isTextDay.length() <= 0 || isTextDay.equals("YES")) {
					for(IntervalConfigBean workShopTypeData:intervalConfigWorkShopTypeList) {
						if (data.getIntervalConfigId() == workShopTypeData.getIntervalConfigId()) { 
							if (dynamicRegionSql.length() > 0) {
								dynamicRegionSql.append("or cal.workshop = '"+workShopTypeData.getWorkShopType()+"'");	
							} else {
								dynamicRegionSql.append("cal.workshop = '"+workShopTypeData.getWorkShopType()+"'");
							}
						}
					}
					if(strandedCarList != null && strandedCarList.size()>0) {
						for (VehicleCarInformationBean vehicleCarInformationBean:strandedCarList) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							List<Date> dateList = reportVehicleRetrospectDao.selectRestDayCount(dynamicRegionSql.toString(),sdf.format(vehicleCarInformationBean.getCompletedTime()));
							int restDayCount = 0;
							long minute = 0;
							if (dateList != null && dateList.size()>0) {
								restDayCount = dateList.size();
								boolean flag = true;
								for (Date date :dateList) {
									try {
										SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
										Date d1=format.parse(format.format(date));
										Date d2=format.parse(format.format(new Date()));
										if(d1.compareTo(d2) == 0) {
											restDayCount = restDayCount -1;
											flag = false;
										}
									} catch (ParseException e) {
										e.printStackTrace();
									}
								}
								if (!flag) {
									long now = System.currentTimeMillis();
							        SimpleDateFormat sdfOne = new SimpleDateFormat("yyyy-MM-dd");
							        try {
										minute = (now - (sdfOne.parse(sdfOne.format(now)).getTime()))/1000/60;
									} catch (ParseException e) {
										e.printStackTrace();
									}
								}
							}	
							if (vehicleCarInformationBean.getRetentionTime() - (restDayCount*24*60 +minute)> data.getRetentionTime()*60) {
							vehicleCarInformationBean.setIntervalName(data.getIntervalName());
							NumberFormat numberFormat = NumberFormat.getInstance();
							numberFormat.setMaximumFractionDigits(1);
							vehicleCarInformationBean.setReturnRetentionTime(numberFormat.format((float)((vehicleCarInformationBean.getRetentionTime() - (restDayCount*24*60+minute)-data.getRetentionTime()*60)/60)));
							vehicleCarInformationlist.add(vehicleCarInformationBean);
						}
					}
				}
			} else {
				if(strandedCarList != null && strandedCarList.size()>0) {
					for (VehicleCarInformationBean vehicleCarInformationBean:strandedCarList) {
						vehicleCarInformationBean.setIntervalName(data.getIntervalName());
						NumberFormat numberFormat = NumberFormat.getInstance();
						numberFormat.setMaximumFractionDigits(1);
						vehicleCarInformationBean.setReturnRetentionTime(numberFormat.format((float)((vehicleCarInformationBean.getRetentionTime()-data.getRetentionTime()*60)/60)));
						vehicleCarInformationlist.add(vehicleCarInformationBean);
					}
				}
			}
		  }
		}
		if (vehicleCarInformationlist!=null && vehicleCarInformationlist.size()>0) {
			this.ListSort(vehicleCarInformationlist);
			count = vehicleCarInformationlist.size();
			List<VehicleCarInformationBean> vehicleCarInformationSizelist = new ArrayList<VehicleCarInformationBean>();
			if(length != 0 && (length+start) <= count) {
				for(int i=start;i<length+start;i++) {	
					vehicleCarInformationSizelist.add(vehicleCarInformationlist.get(i));
				}
			} else if(length != 0 && (length+start) > count) {
				for(int i=start;i<count;i++) {
					vehicleCarInformationSizelist.add(vehicleCarInformationlist.get(i));
				}
			} else {
				for (VehicleCarInformationBean data:vehicleCarInformationlist) {
					vehicleCarInformationSizelist.add(data);
				}
			}
			result.setResultList(vehicleCarInformationSizelist);
			result.setTotalRows(count);
		}
		return result;
}
	
	 //时间排序算法
	private void ListSort(List<VehicleCarInformationBean> list) {
	    Collections.sort(list, new Comparator<VehicleCarInformationBean>() {
	        @Override
	        public int compare(VehicleCarInformationBean o1, VehicleCarInformationBean o2) {
	            try {
	                Date dt1 = o1.getCompletedTime();
	                Date dt2 = o2.getCompletedTime();
	                if (dt1.getTime() < dt2.getTime()) {
	                    return 1;
	                } else if (dt1.getTime() > dt2.getTime()) {
	                    return -1;
	                } else {
	                    return 0;
	                }
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            return 0;
	        }
	    });
	}
}